const request = require('../../utils/request')
const eventBus = require('../../utils/eventBus')  // 添加 eventBus
const analytics = require('../../utils/analytics')  // 引入埋点模块

Page({
  data: {
    courseInfo: null,
    bookingDate: '',
    startDate: '',
    endDate: '',
    timeSlots: ['09:00-10:30', '10:30-12:00', '14:00-15:30', '15:30-17:00', '19:00-20:30'],
    selectedTimeSlot: '',
    contactName: '',
    contactPhone: '',
    remark: ''
  },

  onLoad(options) {
    const { id, title, price, imageUrl } = options
    // 设置日期范围（今天到30天后）
    const today = new Date()
    const end = new Date()
    end.setDate(today.getDate() + 30)

    this.setData({
      courseInfo: {
        id,
        title: decodeURIComponent(title),
        price,
        imageUrl: imageUrl ? decodeURIComponent(imageUrl) : ''
      },
      startDate: this.formatDate(today),
      endDate: this.formatDate(end)
    })
    
    // 记录页面浏览埋点
    analytics.pageView('course_booking', {
      course_id: id,
      course_title: decodeURIComponent(title),
      price: price
    })
  },

  onBack() {
    wx.navigateBack()
  },

  formatDate(date) {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  },

  onDateChange(e) {
    this.setData({ bookingDate: e.detail.value })
  },

  onTimeSlotChange(e) {
    this.setData({ selectedTimeSlot: e.detail.value })
  },

  onContactNameInput(e) {
    this.setData({ contactName: e.detail.value })
  },

  onContactPhoneInput(e) {
    this.setData({ contactPhone: e.detail.value })
  },

  onRemarkInput(e) {
    this.setData({ remark: e.detail.value })
  },

  async onConfirmBooking() {
    const { 
      courseInfo, bookingDate, selectedTimeSlot, 
      contactName, contactPhone, remark, timeSlots 
    } = this.data

    // 表单验证
    if (!bookingDate) {
      return wx.showToast({ title: '请选择上课日期', icon: 'none' })
    }
    if (selectedTimeSlot === '') {
      return wx.showToast({ title: '请选择上课时段', icon: 'none' })
    }
    if (!contactName.trim()) {
      return wx.showToast({ title: '请输入联系人姓名', icon: 'none' })
    }
    if (!/^1\d{10}$/.test(contactPhone)) {
      return wx.showToast({ title: '请输入正确的手机号', icon: 'none' })
    }

    try {
      // 获取当前用户ID
      const app = getApp();
      if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      const userId = app.globalData.userInfo.id;
      
      const result = await request({
        url: '/api/bookings/create',  // 修改这里，从 booking/create 改为 bookings/create
        method: 'POST',
        data: {
          course_id: courseInfo.id,
          booking_date: bookingDate,
          time_slot: timeSlots[selectedTimeSlot],
          contact_name: contactName,
          contact_phone: contactPhone,
          remark,
          userId // 添加用户ID
        }
      })
      
      // 获取返回的预约ID和编号
      const bookingId = result.booking_id;
      const bookingNumber = result.booking_number;
      
      // 也可以使用更通用的track方法记录更多详情
      analytics.track('purchase', parseInt(courseInfo.id), {
        price: parseFloat(courseInfo.price),
        payment_method: 'wechat',
        booking_date: bookingDate,
        time_slot: timeSlots[selectedTimeSlot],
        booking_id: bookingId || null,
        booking_number: bookingNumber || null,
        purchase_type: 'course_booking'
      })

      // 触发预约成功事件
      eventBus.emit('bookingCreated')
      
      // 触发积分更新事件，使首页积分实时更新
      eventBus.emit('pointsUpdate')

      wx.showToast({
        title: '预约成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            wx.navigateBack()
          }, 2000)
        }
      })
    } catch (error) {
      wx.showToast({
        title: error.message || '预约失败，请重试',
        icon: 'none'
      })
    }
  }
})